using MySqlConnector;
using System.Data;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json.Serialization;

namespace FinData.Services
{
    public class UserInfo
    {
        [JsonPropertyName("UserId")]
        public int Id { get; set; }
        
        [JsonPropertyName("username")]
        public required string Username { get; set; }
        
        [JsonPropertyName("lastLogin")]
        public DateTime? LastLogin { get; set; }
        
        [JsonPropertyName("createdAt")]
        public DateTime CreatedAt { get; set; }
        
        [JsonPropertyName("role")]
        public string? Role { get; set; }
    }

    public class ForumPostStats
    {
        [JsonPropertyName("postCount")]
        public int PostCount { get; set; }
        
        [JsonPropertyName("commentCount")]
        public int CommentCount { get; set; }
        
        [JsonPropertyName("likeCount")]
        public int LikeCount { get; set; }
    }
    
    public class BaiduPanLink
    {
        [JsonPropertyName("id")]
        public int Id { get; set; }
        
        [JsonPropertyName("type")]
        public string Type { get; set; } // 'stock', 'index', 'financial'
        
        [JsonPropertyName("fileName")]
        public string FileName { get; set; }
        
        [JsonPropertyName("link")]
        public string Link { get; set; }
        
        [JsonPropertyName("code")]
        public string Code { get; set; }
        
        [JsonPropertyName("updatedAt")]
        public DateTime UpdatedAt { get; set; }
        
        [JsonPropertyName("updatedBy")]
        public int UpdatedBy { get; set; }
        
        [JsonPropertyName("adminName")]
        public string AdminName { get; set; }
    }

    public class DatabaseService
    {
        private readonly string _connectionString;
        private readonly int _maxRetryCount = 3;
        private readonly int _retryDelay = 2000; // 毫秒

        private readonly string _createUsersTableSql = @"
            CREATE TABLE IF NOT EXISTS users (
                id INT AUTO_INCREMENT PRIMARY KEY,
                username VARCHAR(50) NOT NULL UNIQUE,
                password_hash VARCHAR(255) NOT NULL,
                password_salt VARCHAR(255) NOT NULL,
                security_answer VARCHAR(255) NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                last_login TIMESTAMP NULL
            );";

        private readonly string _createFavoritesTableSql = @"
            CREATE TABLE IF NOT EXISTS favorites (
                id INT AUTO_INCREMENT PRIMARY KEY,
                user_id INT NOT NULL,
                stock_code VARCHAR(10) NOT NULL,
                stock_name VARCHAR(50),
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                UNIQUE KEY user_stock (user_id, stock_code),
                FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
            );";

        private readonly string _createPostsTableSql = @"
            CREATE TABLE IF NOT EXISTS forum_posts (
                id INT AUTO_INCREMENT PRIMARY KEY,
                user_id INT NULL,
                title VARCHAR(200) NOT NULL,
                content TEXT NOT NULL,
                view_count INT DEFAULT 0,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL
            );";

        private readonly string _createCommentsTableSql = @"
            CREATE TABLE IF NOT EXISTS forum_comments (
                id INT AUTO_INCREMENT PRIMARY KEY,
                post_id INT NOT NULL,
                user_id INT NOT NULL,
                content TEXT NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (post_id) REFERENCES forum_posts(id) ON DELETE CASCADE,
                FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
            );";

        private readonly string _createLikesTableSql = @"
            CREATE TABLE IF NOT EXISTS forum_likes (
                id INT AUTO_INCREMENT PRIMARY KEY,
                post_id INT NOT NULL,
                user_id INT NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                UNIQUE KEY user_post (user_id, post_id),
                FOREIGN KEY (post_id) REFERENCES forum_posts(id) ON DELETE CASCADE,
                FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
            );";

        private readonly string _createTagsTableSql = @"
            CREATE TABLE IF NOT EXISTS forum_tags (
                id INT AUTO_INCREMENT PRIMARY KEY,
                name VARCHAR(50) NOT NULL UNIQUE,
                count INT DEFAULT 0,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );";

        private readonly string _createPostTagsTableSql = @"
            CREATE TABLE IF NOT EXISTS forum_post_tags (
                id INT AUTO_INCREMENT PRIMARY KEY,
                post_id INT NOT NULL,
                tag_id INT NOT NULL,
                UNIQUE KEY post_tag (post_id, tag_id),
                FOREIGN KEY (post_id) REFERENCES forum_posts(id) ON DELETE CASCADE,
                FOREIGN KEY (tag_id) REFERENCES forum_tags(id) ON DELETE CASCADE
            );";

        private readonly string _createPostImagesTableSql = @"
            CREATE TABLE IF NOT EXISTS forum_post_images (
                id INT AUTO_INCREMENT PRIMARY KEY,
                post_id INT NOT NULL,
                image_path VARCHAR(255) NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (post_id) REFERENCES forum_posts(id) ON DELETE CASCADE
            );";

        private readonly string _createReportsTableSql = @"
            CREATE TABLE IF NOT EXISTS forum_reports (
                id INT AUTO_INCREMENT PRIMARY KEY,
                post_id INT NOT NULL,
                user_id INT NOT NULL,
                reason VARCHAR(100) NOT NULL,
                detail TEXT,
                status VARCHAR(20) DEFAULT 'pending',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                FOREIGN KEY (post_id) REFERENCES forum_posts(id) ON DELETE CASCADE,
                FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
            );";

        private readonly string _createUserPunishmentsTableSql = @"
            CREATE TABLE IF NOT EXISTS user_punishments (
                id INT AUTO_INCREMENT PRIMARY KEY,
                user_id INT NOT NULL,
                punishment_type VARCHAR(50) NOT NULL,
                start_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                end_date TIMESTAMP,
                reason TEXT,
                related_report_id INT,
                created_by INT,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
                FOREIGN KEY (related_report_id) REFERENCES forum_reports(id) ON DELETE SET NULL,
                FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL
            );";

        private readonly string _createBaiduPanLinksTableSql = @"
            CREATE TABLE IF NOT EXISTS baidu_pan_links (
                id INT AUTO_INCREMENT PRIMARY KEY,
                type VARCHAR(20) NOT NULL,
                file_name VARCHAR(100) NOT NULL,
                link TEXT NOT NULL,
                code VARCHAR(10) NOT NULL,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_by INT NOT NULL,
                INDEX (type),
                INDEX (updated_by)
            );";

        public DatabaseService()
        {
            // 配置数据库连接字符串，优先使用环境变量
            var connectionString = Environment.GetEnvironmentVariable("ConnectionStrings__DefaultConnection");
            _connectionString = string.IsNullOrEmpty(connectionString) 
                ? "Server=localhost;Port=3306;Database=findata;User=root;Password=root;"
                : connectionString;
            
            Console.WriteLine($"使用数据库连接: {_connectionString.Replace("Password=root", "Password=****")}");
        }

        /// <summary>
        /// 获取数据库连接
        /// </summary>
        /// <returns>MySqlConnection对象</returns>
        public MySqlConnection GetConnection()
        {
            return new MySqlConnection(_connectionString);
        }

        /// <summary>
        /// 测试数据库连接
        /// </summary>
        /// <returns>连接成功返回true，否则返回false</returns>
        public async Task<bool> TestConnectionAsync()
        {
            try
            {
                using (var connection = new MySqlConnection(_connectionString))
                {
                    await connection.OpenAsync();
                    Console.WriteLine("数据库连接测试成功");
                    return true;
                }
            }
            catch (MySqlException ex)
            {
                Console.WriteLine($"数据库连接测试失败: {ex.Message}");
                Console.WriteLine($"错误代码: {ex.Number}");
                // 常见错误代码：
                // 1042: 无法连接到主机
                // 1045: 用户名或密码错误
                // 1049: 数据库不存在
                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"数据库连接测试失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 初始化数据库，创建必要的表
        /// </summary>
        public async Task InitializeDatabaseAsync()
        {
            int retryCount = 0;
            while (true)
            {
                try
                {
                    using (var connection = new MySqlConnection(_connectionString))
                    {
                        await connection.OpenAsync();
                        Console.WriteLine("数据库连接成功");
                        
                        Console.WriteLine("=== 开始创建必要的数据库表 ===");
                        
                        // 创建用户表
                        Console.WriteLine("创建用户表(users)...");
                        using (var cmd = new MySqlCommand(_createUsersTableSql, connection))
                        {
                            await cmd.ExecuteNonQueryAsync();
                        }
                        
                        // 创建收藏表
                        Console.WriteLine("创建收藏表(favorites)...");
                        using (var cmd = new MySqlCommand(_createFavoritesTableSql, connection))
                        {
                            await cmd.ExecuteNonQueryAsync();
                        }
                        
                        // 创建论坛帖子表
                        Console.WriteLine("创建论坛帖子表(forum_posts)...");
                        using (var cmd = new MySqlCommand(_createPostsTableSql, connection))
                        {
                            await cmd.ExecuteNonQueryAsync();
                        }
                        
                        // 创建论坛标签表
                        Console.WriteLine("创建论坛标签表(forum_tags)...");
                        using (var cmd = new MySqlCommand(_createTagsTableSql, connection))
                        {
                            await cmd.ExecuteNonQueryAsync();
                        }
                        
                        // 创建论坛评论表
                        Console.WriteLine("创建论坛评论表(forum_comments)...");
                        using (var cmd = new MySqlCommand(_createCommentsTableSql, connection))
                        {
                            await cmd.ExecuteNonQueryAsync();
                        }
                        
                        // 创建论坛点赞表
                        Console.WriteLine("创建论坛点赞表(forum_likes)...");
                        using (var cmd = new MySqlCommand(_createLikesTableSql, connection))
                        {
                            await cmd.ExecuteNonQueryAsync();
                        }
                        
                        // 创建帖子标签关联表
                        Console.WriteLine("创建帖子标签关联表(forum_post_tags)...");
                        using (var cmd = new MySqlCommand(_createPostTagsTableSql, connection))
                        {
                            await cmd.ExecuteNonQueryAsync();
                        }
                        
                        // 创建帖子图片表
                        Console.WriteLine("创建帖子图片表(forum_post_images)...");
                        using (var cmd = new MySqlCommand(_createPostImagesTableSql, connection))
                            {
                                await cmd.ExecuteNonQueryAsync();
                        }
                        
                        // 创建举报表
                        Console.WriteLine("创建举报表(forum_reports)...");
                        using (var cmd = new MySqlCommand(_createReportsTableSql, connection))
                            {
                                await cmd.ExecuteNonQueryAsync();
                        }

                        // 创建用户惩罚表
                        Console.WriteLine("创建用户惩罚表(user_punishments)...");
                        using (var cmd = new MySqlCommand(_createUserPunishmentsTableSql, connection))
                            {
                                await cmd.ExecuteNonQueryAsync();
                        }
                        
                        // 创建百度网盘链接表
                        Console.WriteLine("创建百度网盘链接表(baidu_pan_links)...");
                        using (var cmd = new MySqlCommand(_createBaiduPanLinksTableSql, connection))
                                {
                                    await cmd.ExecuteNonQueryAsync();
                        }
                        
                        Console.WriteLine("=== 数据库初始化成功 - 所有必要的表已创建 ===");
                        connection.Close();
                        break; // 成功后跳出循环
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"初始化数据库时发生错误: {ex}");
                    
                    // 检查是否需要重试
                    if (++retryCount >= _maxRetryCount)
                    {
                        Console.WriteLine($"已达到最大重试次数({_maxRetryCount})，初始化失败");
                        throw;
                    }
                    
                    Console.WriteLine($"将在{_retryDelay/1000}秒后重试...");
                    await Task.Delay(_retryDelay);
                }
            }
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>用户信息对象，如果用户不存在则返回null</returns>
        public async Task<UserInfo?> GetUserInfoAsync(int userId)
        {
            try
            {
                using (var connection = new MySqlConnection(_connectionString))
                {
                    await connection.OpenAsync();

                    string query = "SELECT id, username, last_login, created_at FROM users WHERE id = @UserId";
                    using (var cmd = new MySqlCommand(query, connection))
                    {
                        cmd.Parameters.AddWithValue("@UserId", userId);

                        using (var reader = await cmd.ExecuteReaderAsync())
                        {
                            if (await reader.ReadAsync())
                            {
                                return new UserInfo
                                {
                                    Id = reader.GetInt32(0),
                                    Username = reader.GetString(1),
                                    LastLogin = reader.IsDBNull(2) ? null : reader.GetDateTime(2),
                                    CreatedAt = reader.GetDateTime(3),
                                    Role = "user" // 默认角色
                                };
                            }
                            return null;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取用户信息失败: {ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 创建密码哈希和盐值
        /// </summary>
        /// <param name="password">原始密码</param>
        /// <returns>返回(哈希密码，盐值)</returns>
        private (string hash, string salt) CreatePasswordHash(string password)
        {
            // 生成随机盐值
            byte[] saltBytes = new byte[32];
            using (var rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(saltBytes);
            }
            string salt = Convert.ToBase64String(saltBytes);

            // 计算哈希
            string hash = ComputeHash(password, salt);

            return (hash, salt);
        }

        /// <summary>
        /// 根据密码和盐值计算哈希
        /// </summary>
        /// <param name="password">原始密码</param>
        /// <param name="salt">盐值</param>
        /// <returns>哈希密码</returns>
        private string ComputeHash(string password, string salt)
        {
            byte[] saltBytes = Convert.FromBase64String(salt);
            byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
            
            // 合并密码和盐值
            byte[] combined = new byte[passwordBytes.Length + saltBytes.Length];
            Buffer.BlockCopy(passwordBytes, 0, combined, 0, passwordBytes.Length);
            Buffer.BlockCopy(saltBytes, 0, combined, passwordBytes.Length, saltBytes.Length);
            
            // 计算哈希
            byte[] hashBytes;
            using (var sha256 = SHA256.Create())
            {
                hashBytes = sha256.ComputeHash(combined);
            }
            
            return Convert.ToBase64String(hashBytes);
        }

        /// <summary>
        /// 验证密码
        /// </summary>
        /// <param name="password">输入的密码</param>
        /// <param name="storedHash">存储的哈希</param>
        /// <param name="storedSalt">存储的盐值</param>
        /// <returns>密码是否匹配</returns>
        private bool VerifyPassword(string password, string storedHash, string storedSalt)
        {
            // 使用相同的盐值计算哈希
            string computedHash = ComputeHash(password, storedSalt);
            Console.WriteLine($"验证密码: 存储的哈希 vs. 计算的哈希");
            Console.WriteLine($"存储的: {storedHash}");
            Console.WriteLine($"计算的: {computedHash}");
            
            // 比较哈希
            return string.Equals(computedHash, storedHash);
        }

        /// <summary>
        /// 用户登录验证
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns>验证成功返回用户ID，失败返回-1</returns>
        public async Task<int> ValidateUserAsync(string username, string password)
        {
            try
            {
                using (var connection = new MySqlConnection(_connectionString))
                {
                    await connection.OpenAsync();

                    // 查询用户
                    string query = "SELECT id, password_hash, password_salt FROM users WHERE username = @Username";
                    using (var cmd = new MySqlCommand(query, connection))
                    {
                        cmd.Parameters.AddWithValue("@Username", username);

                        using (var reader = await cmd.ExecuteReaderAsync())
                        {
                            if (await reader.ReadAsync())
                            {
                                int userId = reader.GetInt32(0);
                                string storedHash = reader.GetString(1);
                                string storedSalt = reader.GetString(2);

                                Console.WriteLine($"找到用户 {username}，ID: {userId}");

                                // 验证密码
                                if (VerifyPassword(password, storedHash, storedSalt))
                                {
                                    // 更新最后登录时间
                                    await UpdateLastLoginAsync(userId);
                                    return userId;
                                }
                                else
                                {
                                    Console.WriteLine("密码验证失败");
                                    return -1;
                                }
                            }
                            else
                            {
                                Console.WriteLine($"用户 {username} 不存在");
                                return -1;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"验证用户失败: {ex.Message}");
                return -1;
            }
        }

        /// <summary>
        /// 注册新用户
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="securityAnswer">安全问题答案</param>
        /// <returns>注册成功返回true，失败返回false</returns>
        public async Task<bool> RegisterUserAsync(string username, string password, string securityAnswer)
        {
            try
            {
                using (var connection = new MySqlConnection(_connectionString))
                {
                    await connection.OpenAsync();

                    // 检查用户名是否已存在
                    string checkQuery = "SELECT COUNT(*) FROM users WHERE username = @Username";
                    using (var cmd = new MySqlCommand(checkQuery, connection))
                    {
                        cmd.Parameters.AddWithValue("@Username", username);
                        int count = Convert.ToInt32(await cmd.ExecuteScalarAsync());
                        if (count > 0)
                        {
                            Console.WriteLine($"用户名 {username} 已存在");
                            return false;
                        }
                    }

                    // 生成密码哈希和盐值
                    var (hash, salt) = CreatePasswordHash(password);

                    // 插入新用户
                    string query = @"
                        INSERT INTO users (username, password_hash, password_salt, security_answer)
                        VALUES (@Username, @PasswordHash, @PasswordSalt, @SecurityAnswer)";

                    using (var cmd = new MySqlCommand(query, connection))
                    {
                        cmd.Parameters.AddWithValue("@Username", username);
                        cmd.Parameters.AddWithValue("@PasswordHash", hash);
                        cmd.Parameters.AddWithValue("@PasswordSalt", salt);
                        cmd.Parameters.AddWithValue("@SecurityAnswer", securityAnswer);

                        int rowsAffected = await cmd.ExecuteNonQueryAsync();
                        return rowsAffected > 0;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"注册用户失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 根据用户名和安全问题答案重置密码
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="securityAnswer">安全问题答案</param>
        /// <param name="newPassword">新密码</param>
        /// <returns>重置成功返回true，失败返回false</returns>
        public async Task<bool> ResetPasswordBySecurityAnswerAsync(string username, string securityAnswer, string newPassword)
        {
            try
            {
                using (var connection = new MySqlConnection(_connectionString))
                {
                    await connection.OpenAsync();

                    // 先检查用户是否存在以及安全问题答案是否正确
                    string checkQuery = "SELECT id, security_answer FROM users WHERE username = @Username";
                    using (var checkCmd = new MySqlCommand(checkQuery, connection))
                    {
                        checkCmd.Parameters.AddWithValue("@Username", username);
                        
                        using (var reader = await checkCmd.ExecuteReaderAsync())
                        {
                            if (!await reader.ReadAsync())
                            {
                                Console.WriteLine($"重置密码失败: 用户 {username} 不存在");
                                return false; // 用户不存在
                            }

                            int userId = reader.GetInt32(0);
                            string storedSecurityAnswer = reader.GetString(1);

                            // 验证安全问题答案
                            if (storedSecurityAnswer != securityAnswer)
                            {
                                Console.WriteLine($"重置密码失败: 用户 {username} 的安全问题答案不正确");
                                return false; // 安全问题答案不正确
                            }
                        }
                    }

                    // 创建新的密码哈希和盐值
                    var (passwordHash, passwordSalt) = CreatePasswordHash(newPassword);
                    Console.WriteLine($"为用户 {username} 创建新的密码哈希: {passwordHash.Substring(0, 20)}..., 盐值: {passwordSalt.Substring(0, 20)}...");

                    // 更新密码
                    string updateQuery = @"
                        UPDATE users 
                        SET password_hash = @PasswordHash, password_salt = @PasswordSalt 
                        WHERE username = @Username";
                    
                    using (var updateCmd = new MySqlCommand(updateQuery, connection))
                    {
                        updateCmd.Parameters.AddWithValue("@Username", username);
                        updateCmd.Parameters.AddWithValue("@PasswordHash", passwordHash);
                        updateCmd.Parameters.AddWithValue("@PasswordSalt", passwordSalt);
                        
                        int rowsAffected = await updateCmd.ExecuteNonQueryAsync();
                        Console.WriteLine($"更新用户 {username} 密码结果: {rowsAffected > 0}");
                        return rowsAffected > 0;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"重置密码失败: {ex.Message}");
                Console.WriteLine($"异常详情: {ex}");
                return false;
            }
        }

        private async Task UpdateLastLoginAsync(int userId)
        {
            try
            {
                using (var connection = new MySqlConnection(_connectionString))
                {
                    await connection.OpenAsync();

                    string updateQuery = "UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE id = @UserId";
                    using (var updateCmd = new MySqlCommand(updateQuery, connection))
                    {
                        updateCmd.Parameters.AddWithValue("@UserId", userId);
                        await updateCmd.ExecuteNonQueryAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"更新最后登录时间失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取特定类型的百度网盘链接
        /// </summary>
        /// <param name="type">链接类型</param>
        /// <returns>百度网盘链接信息</returns>
        public async Task<BaiduPanLink> GetBaiduPanLinkByTypeAsync(string type)
        {
            try
            {
                using (var connection = new MySqlConnection(_connectionString))
                {
                    await connection.OpenAsync();
                    
                    string query = @"
                        SELECT b.id, b.type, b.file_name, b.link, b.code, b.updated_at, b.updated_by, a.username as admin_name
                        FROM baidu_pan_links b
                        LEFT JOIN admins a ON b.updated_by = a.id
                        WHERE b.type = @Type
                        ORDER BY b.updated_at DESC
                        LIMIT 1";
                    
                    using (var command = new MySqlCommand(query, connection))
                    {
                        command.Parameters.AddWithValue("@Type", type);
                        
                        using (var reader = await command.ExecuteReaderAsync())
                        {
                            if (await reader.ReadAsync())
                            {
                                return new BaiduPanLink
                                {
                                    Id = reader.GetInt32("id"),
                                    Type = reader.GetString("type"),
                                    FileName = reader.GetString("file_name"),
                                    Link = reader.GetString("link"),
                                    Code = reader.GetString("code"),
                                    UpdatedAt = reader.GetDateTime("updated_at"),
                                    UpdatedBy = reader.GetInt32("updated_by"),
                                    AdminName = reader.IsDBNull("admin_name") ? "未知" : reader.GetString("admin_name")
                                };
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取百度网盘链接失败: {ex.Message}");
            }
            
            return null;
        }
    }
} 